#include <stdio.h>
#include <stdint.h>
#include <unistd.h>

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>

#include <pthread.h>

#include "libtest.h"

void *fifo_read(void *argv)
{
    char *path = (char *)argv;
    int fd_read = open(path, O_RDONLY);
    size_t ret;
    uint8_t buff[1024 * 512];

    if (fd_read < 1)
    {
        printf("%s: open %s failed \r\n", __func__, path);
        return NULL;
    }

    while(1)
    {
        ret = read(fd_read, buff, sizeof(buff));
        if (ret > 0)
            printf("fifo recv %d \r\n", ret);
        else if (ret < 0)
        {
            printf("fifo read error\r\n");
            break;
        }
    }

    close(fd_read);
    return NULL;
}

int main(int argc, char **argv)
{
    char fifoPath[] = "/tmp/fifo-test";
    int fd_write;
    pthread_t th;
    int ret;

    printf("\n************************************************\n");
    printf("\n\t\t myapp !\n");
    printf("\n************************************************\n\n");

    libtest_api();

    ret = mkfifo(fifoPath, 0666);
    if (ret < 0)
    {
        printf("mkfifo failed (%d)\r\n", ret);
        return -1;
    }

    fd_write = open(fifoPath, O_WRONLY);
    if (fd_write < 1)
    {
        printf("open %s failed \r\n", fifoPath);
        return -1;
    }

    pthread_create(&th, NULL, fifo_read, (void*)fifoPath);
    usleep(1000);

    while (1)
    {
        if (write(fd_write, "123456789\n", 10) != 10)
        {
            printf("fifo write error ...\r\n");
            break;
        }
        sleep(1);
    }

    close(fd_write);
    pthread_join(th, NULL);
    return 0;
}
